package filmsystem.example.film.controllers;

import filmsystem.example.film.dao.FilmRepository;
import filmsystem.example.film.dao.ViewRepository;
import filmsystem.example.film.entities.Film;
import filmsystem.example.film.entities.View;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("view")
public class ViewController {

    @Autowired
    ViewRepository viewRepository;

    @Autowired
    FilmRepository filmRepository;

    @GetMapping("/new")
    public String displayViewForm(Model model){

        View aView = new View();
        List<Film> films = filmRepository.findAll();
        model.addAttribute("view",aView);
        model.addAttribute("allFilms",films);
        return "user/new-view";
    }

    @PostMapping("/save")
    public String createView(Model model,@RequestParam List<Long> films, View view){

        viewRepository.save(view);
        Iterable<Film> chosenFilms = filmRepository.findAllById(films);

        for (Film film : chosenFilms){
            film.setView(view);
            filmRepository.save(film);
        }
        return "redirect:/view/new";
    }
}
